package cn.sdhuijin.controller;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.sdhuijin.service.StandardService;
import cn.sdhuijin.utils.ReadExcel;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年5月6日 下午3:00:35 类说明
 */
@Controller
public class StandardController {

	@Inject
	private StandardService standardService;

	@RequestMapping(value = { "/upload" }, method = RequestMethod.POST)
	@ResponseBody
	public void uploadExcel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 转型为MultipartHttpRequest：
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile file = multipartRequest.getFile("uploadfile");

		List<List<Object>> list = ReadExcel.readExcel(file, 0, 7);
		List<List<Object>> targetList = ReadExcel.readExcel(file, 1, 3);
		List<List<Object>> deductionUserList = ReadExcel.readExcel(file, 2, 3);
		response.setContentType("text/html");
		String result = "";
		if (list.get(0).size() >= 7) {
			try {
				standardService.BatchImport(list);
				standardService.ImportStandardTarget(targetList);
				standardService.ImportStandardDeductionUser(deductionUserList);
				result = "{success:true,message:'导入成功'}";
			} catch (NumberFormatException e) {
				result = "{success:false,message:'" + e.getMessage() + "'}";
			} catch (Exception e) {
				result = "{success:false,message:'导入失败！  " + e.getMessage()
						+ "'}";
				e.printStackTrace();
			}
		} else {
			result = "{success:false,message:'导入格式不正确，请您按照模板导入数据'}";
		}
		response.getWriter().write(result);
	}

}
